﻿
/****** Object:  User Defined Function dbo.ValidateBankRoutingNumber    Script Date: 10/14/2009 10:39:06 PM ******/
CREATE FUNCTION ValidateBankRoutingNumber  ( @strRoutingNumber varchar(9) )  
RETURNS bit AS  
BEGIN 
	declare  @iSum int
	declare @iWeight int 
	declare @iDigit int
	declare @iCount int

	set @iSum = 0	
	set @iWeight = 3

	if  len( @strRoutingNumber )  != 9 
		return 0
	set @iCount = 0
	while @iCount < 8
	begin
		set @iDigit = ascii( substring( @strRoutingNumber, @iCount + 1, 1 ) )  - ascii( '0' )
		
		set @iSum = @iSum + ( ( @iDigit * @iWeight ) % 10 )
		
		if @iWeight = 3 
			set @iWeight = 7
		else if @iWeight = 7 
			set @iWeight = 1
		else
			set @iWeight = 3

		set @iCount = @iCount + 1
	end
	set @iDigit = ascii( substring( @strRoutingNumber, 9, 1 ) )  - ascii( '0' )
	
	return case when @iDigit = ( 10 - ( @iSum % 10 ) ) % 10  then 1 else 0 end
END

